import { Form, Row, Col, Input, Button, Table, Spin, Space, message, Select, List, Empty } from 'antd';
import { Ref, useContext, useMemo, useRef, useState } from 'react';

import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { onCloseModalCommon } from '@/utils';
import { Descriptions, useDescriptions } from '@/components/Descriptions';
import { SearchOutlined, RedoOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { SelectBankService, getSupplierDataGrid } from '../services/UpdateService';
import { SourceUpdateContext } from '../common/UpdateContext';
import { ColumnsRenderFun } from '../../Acommon';
import { SourceUpdateAPI } from '../common/type';
import { RowSelectionType } from 'antd/lib/table/interface';
import { addSupplierInfoService } from '@/pages/SupplierManage/services';
import { commonPageSizeOptions } from '@/common/constVariable';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import _ from 'lodash';
import InfiniteScroll from 'react-infinite-scroller';
import '../common/style.less';

/**
 * @SupplierModal 供应商弹窗组件
 * @param onSave 保存事件
 * @param onClose 关闭事件
 * @returns
 */

const SupplierModal = ({ onSave, onClose, dataList, selectType }: SourceUpdateAPI.SupplierModalProps) => {
  /** 上下文解构 */
  const { curRes } = useContext(SourceUpdateContext);
  /** 弹窗Ref */
  const oneModalRef: Ref<IOneModalRef> = useRef(null);
  /** 新增表格表单与列表渲染状态 */
  const [isShowList, setIsShowList] = useState<boolean>(true);
  /** 列表接口 */
  const { data, loading, reloadRequest, pagination, supplierTableProps } = getSupplierDataGrid(curRes);
  /** 表单Ref */
  const [contactFormRef] = Form.useForm();
  /** 企业属性标记 */
  const [enterType, setEnterType] = useState(0);
  /** 开户行select受控模式 */
  const [open, setOpen] = useState(false);
  /** 数据值 */
  const [searchVal, setSearchVal] = useState<string | undefined>();
  /** 保存的分页参数 */
  const [scrollObj, setScrollObj] = useState<any>({
    total: 0,
    count: 1,
    loading: false,
    hasMore: true,
    limit: 10,
  });

  /**
   * 获取数据
   * */
  const { loading: bankLoading, getBankRun, reloadRefresh, datas, paginations } = SelectBankService((res) => {
    if (res && res?.msgFlag) {
      // setManageDataList(res?.rows);
      setScrollObj({
        ...scrollObj,
        loading: false,
        hasMore: true,
        total: res.total,
      });
    } else {
      message.error(res?.msg);
    }
  });

  /** 初始化获取数据 */
  const defaultGetWarnData = () => {
    let { count, limit } = scrollObj;
    count++;
    setScrollObj({
      ...scrollObj,
      count: count,
      loading: true,
    });
    let payload: Record<string, any> = {
      current: 1,
      pageSize: count * 10 + limit,
      // bankName: searchVal,
    };
    if (searchVal) {
      payload.bankName = searchVal?.split(' ')?.join(',');
    }
    getBankRun(payload);
  };

  /** 滚动加载 */
  const handleInfiniteOnLoad = () => {
    const { total } = scrollObj;
    if (Number(datas?.rows?.length) >= total) {
      message.warning('没有更多数据了！');
      setScrollObj({
        ...scrollObj,
        hasMore: false,
        loading: false,
      });
      return;
    }
    defaultGetWarnData();
  };

  const columns = [
    {
      title: '单位名称',
      dataIndex: 'fullName',
      key: 'fullName',
      width: 200,
      render: (text: string) => ColumnsRenderFun({ text, isTooltip: true }),
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'creditID',
      key: 'creditID',
      width: 200,
      render: (text: string) => ColumnsRenderFun({ text, isTooltip: true }),
    },
    {
      title: '法人代表',
      dataIndex: 'legalName',
      key: 'legalName',
      width: 140,
      render: (text: string) => ColumnsRenderFun({ text }),
    },
    // {
    //   title: '授权代表',
    //   dataIndex: 'authName',
    //   key: 'authName',
    //   width: 140,
    //   render: (text: string) => ColumnsRenderFun({ text }),
    // },
    {
      title: '单位地址',
      dataIndex: 'workAddress',
      key: 'workAddress',
      width: 140,
      render: (text: string) => ColumnsRenderFun({ text, isTooltip: true }),
    },
    {
      title: '联系人',
      dataIndex: 'contactName',
      key: 'contactName',
      width: 140,
      render: (text: string) => ColumnsRenderFun({ text }),
    },
    {
      title: '联系电话',
      dataIndex: 'contactMobile',
      key: 'contactMobile',
      width: 140,
      render: (text: string) => ColumnsRenderFun({ text }),
    },
  ];

  const [config, basicForm] = useDescriptions({
    name: 'source-info',
    labelWidth: 220,
    schemas: [
      {
        label: '新增供应商',
        field: 'title',
        component: 'Title',
      },
      {
        label: '单位名称',
        field: 'fullName',
        component: 'Input',
        required: true,
        placeholder: '请输入',
      },
      {
        label: '企业属性',
        field: 'enterpriseType',
        component: 'Render',
        required: true,
        placeholder: '请输入',
        slotRender: () => {
          return (
            <>
              <TagSelect
                formLabel=""
                formName="enterpriseType"
                formRequired={true}
                radioList={[
                  {
                    value: 0,
                    name: '大陆',
                  },
                  {
                    value: 1,
                    name: '港澳台',
                  },
                  {
                    value: 2,
                    name: '境外',
                  },
                ]}
                defalultKeys={0}
                onChange={(valNum) => {
                  setEnterType(valNum);
                  if (valNum) {
                    basicForm?.validateFields();
                  }
                }}
              />
            </>
          );
        },
      },
      {
        label: '法定代表人',
        field: 'legalName',
        component: 'Input',
        required: enterType ? false : true,
        placeholder: '请输入',
      },
      {
        label: '所属区域',
        field: 'registerAddress',
        component: 'Input',
        required: false,
        placeholder: '请输入',
      },
      {
        label: '统一社会信用代码',
        field: 'creditID',
        component: 'Input',
        required: enterType ? false : true,
        placeholder: '请输入',
      },
      {
        label: '注册电话',
        field: 'registerPhone',
        component: 'Input',
        required: enterType ? false : true,
        placeholder: '请输入',
      },

      {
        label: '开户行名称',
        field: 'bankName',
        component: 'Render',
        required: enterType ? false : true,
        placeholder: '请输入',
        slotRender: () => {
          return (
            <>
              <Form.Item
                label=""
                name="bankName"
                className="source-bankName-formitemCls"
                rules={
                  enterType
                    ? undefined
                    : [
                        {
                          required: true,
                          message: '请选择开户行',
                        },
                      ]
                }
              >
                <Select
                  open={open}
                  onDropdownVisibleChange={(visible) => setOpen(visible)}
                  allowClear
                  showSearch
                  onSearch={_?.debounce((val) => {
                    if (val) {
                      setSearchVal(val);
                      getBankRun({ current: 1, pageSize: 10, bankName: val?.split(' ')?.join(',') });
                      setScrollObj({
                        ...scrollObj,
                        count: 1,
                      });
                    } else {
                      setSearchVal(undefined);
                      getBankRun({ current: 1, pageSize: 10 });
                      setScrollObj({
                        ...scrollObj,
                        count: 1,
                      });
                    }
                  }, 1000)}
                  onClear={() => {
                    basicForm?.setFieldValue('bankCode', undefined);
                    getBankRun({ current: 1, pageSize: 10 });
                    setScrollObj({
                      ...scrollObj,
                      count: 1,
                    });
                  }}
                  onSelect={(val, node) => basicForm?.setFieldValue('bankCode', node?.key)}
                  filterOption={false}
                  placeholder={'请选择（多关键字用空格隔开）'}
                  dropdownRender={(menu) => (
                    <div className={'bankSelectScrollBox'} style={{ width: '100%', height: '300px' }}>
                      <InfiniteScroll
                        loadMore={handleInfiniteOnLoad}
                        initialLoad={false}
                        pageStart={1}
                        useWindow={false}
                        hasMore={!scrollObj?.loading && scrollObj?.hasMore}
                        loader={
                          scrollObj?.loading ? (
                            <div style={{ textAlign: 'center' }}>
                              <Spin size="small" />
                            </div>
                          ) : (
                            <></>
                          )
                        }
                      >
                        <div className="commonTabsBodyDom">
                          {datas?.rows?.length ? (
                            <div style={{ padding: '0px 5px', cursor: 'pointer' }}>
                              <List
                                itemLayout="horizontal"
                                size="small"
                                dataSource={datas?.rows}
                                renderItem={(item: Record<string, any>) => {
                                  return (
                                    <List.Item
                                      onClick={() => {
                                        basicForm?.setFieldsValue({
                                          bankName: item?.bankName,
                                          bankCode: item?.bankCode,
                                        });
                                        setOpen(false);
                                      }}
                                    >
                                      <List.Item.Meta title={item?.bankName} />
                                    </List.Item>
                                  );
                                }}
                              />
                            </div>
                          ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
                          )}
                        </div>
                      </InfiniteScroll>
                    </div>
                  )}
                ></Select>
              </Form.Item>
            </>
          );
        },
      },
      {
        label: '开户行帐号',
        field: 'bankAccount',
        component: 'Input',
        required: enterType ? false : true,
        placeholder: '请输入',
      },
      {
        label: '银行行号',
        field: 'bankCode',
        disabled: true,
        component: 'Input',
        required: enterType ? false : true,
        placeholder: '自动带出',
      },
      // {
      //   label: '单位电话',
      //   field: 'registerPhone',
      //   component: 'Input',
      //   required: enterType ? false : true,
      //   placeholder: '请输入',
      // },
      {
        label: '单位地址',
        field: 'workAddress',
        component: 'Input',
        required: enterType ? false : true,
        // colSpan: 2,
        placeholder: '请输入',
      },
      {
        label: '首要联系人',
        field: 'contactName',
        component: 'Input',
        required: enterType ? false : true,
        placeholder: '请输入',
      },
      {
        label: '联系电话',
        field: 'contactMobile',
        component: 'Input',
        required: enterType ? false : true,
        placeholder: '请输入',
      },
    ],
  });

  // 选中表格id集合
  const [selectedRow, setSelectedRow] = useState<Record<string, any>[]>([]);

  const updateSupplierCallback = (res: Record<string, any>, updateType: boolean) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      setIsShowList(true);
      reloadRequest({});
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入添加接口 */
  const { addSupplierInfoRun, addSupplierInfoLoading } = addSupplierInfoService(updateSupplierCallback);
  /**确认*/
  const onModalOk = () => {
    if (!isShowList) {
      Promise?.all([basicForm?.validateFields(), contactFormRef.validateFields()])?.then((res) => {
        addSupplierInfoRun({
          ...basicForm.getFieldsValue(),
          ...contactFormRef.getFieldsValue(),
        });
      });
      return;
    }
    onSave(selectedRow);
    onCloseModalCommon(oneModalRef);
  };

  /**
   * 表单Form
   * */
  const [searchForm] = Form.useForm();

  /**
   * @onSelectChange 复选框change事件
   * @param keys 表格ID
   * */
  const onSelectChange = (record: React.Key[], rows: Record<string, any>[]) => {
    setSelectedRow(rows);
  };

  /** 搜索 */
  const onSearch = async () => {
    const result = await searchForm?.validateFields();
    reloadRequest({ ...result, current: 1, pageSize: 10 });
  };

  /** 重置 */
  const onReset = async () => {
    await searchForm?.resetFields();
    reloadRequest({ current: 1, pageSize: 10 });
  };

  /** 表格项是否禁用 */
  const tableDisable = useMemo(() => {
    const idList = dataList?.map((item) => item?.supplierID);
    return idList;
  }, [dataList]);

  // 底部按钮
  const footerRender = () => {
    return (
      <>
        {curRes?.['/purchaseSourceSupplierController/addSupplier'] && (
          <Button type={'primary'} onClick={() => setIsShowList(!isShowList)}>
            {isShowList ? '添加供应商' : '选择供应商'}
          </Button>
        )}
        <Button onClick={() => onCloseModalCommon(oneModalRef)}>取消</Button>
        <Button type={'primary'} onClick={onModalOk}>
          确认
        </Button>
      </>
    );
  };

  /** 表格分页方法改变事件 */
  const handlePaginationChange = (current, pageSize, params) => {
    reloadRequest({ pageSize, current, ...params, ...searchForm.getFieldsValue() });
  };

  return (
    <OneModal
      open={true}
      onCancel={onClose}
      centered={true}
      title={isShowList ? '选择供应商' : '添加供应商'}
      bodyStyle={{
        height: document.body.clientHeight * 0.6,
        padding: '5px 0px',
      }}
      width={document.body.clientWidth * 0.65}
      ref={oneModalRef}
      footer={footerRender()}
    >
      <div className="source-update-selectSupplier">
        <Spin spinning={false} style={{ height: '100%', overflow: 'hidden' }}>
          {!isShowList && (
            <div style={{ padding: '16px' }}>
              <Spin spinning={addSupplierInfoLoading}>
                {/* 供应商基本信息 */}
                <Descriptions config={config} />
                {/* 添加n个联系人 */}
                <Form form={contactFormRef} name="dynamic_form_complex" autoComplete="off" className="dynamic_form_complex">
                  <Form.List name="msupplierContacterList">
                    {(fields, { add, remove }) => (
                      <>
                        {fields.map((field, index) => (
                          <Row key={field.key} className={'source-update-selectSupplier-contactPerson'}>
                            <Col span={12}>
                              <Form.Item shouldUpdate={(prevValues, curValues) => prevValues.fullName !== curValues.fullName}>
                                {() => (
                                  <Form.Item {...field} label={`联系人`} name={[field.name, `fullName`]} rules={[{ required: true, message: '请输入姓名' }]}>
                                    <Input bordered={false} placeholder="请输入" />
                                  </Form.Item>
                                )}
                              </Form.Item>
                            </Col>
                            <Col span={11}>
                              <Form.Item {...field} label={`联系电话`} name={[field.name, `phoneMobile`]} rules={[{ required: true, message: '请输入电话' }]}>
                                <Input bordered={false} placeholder="请输入" />
                              </Form.Item>
                            </Col>
                            <Col span={1} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                              <MinusCircleOutlined onClick={() => remove(field.name)} />
                            </Col>
                          </Row>
                        ))}

                        <Form.Item>
                          <Button type="dashed" onClick={() => add()} icon={<PlusOutlined />}>
                            添加联系人
                          </Button>
                        </Form.Item>
                      </>
                    )}
                  </Form.List>
                </Form>
              </Spin>
            </div>
          )}
          {isShowList && (
            <div className="source-update-selectSupplier-boxDiv">
              <Form form={searchForm}>
                <Row gutter={[8, 0]} style={{ padding: '10px 1rem 0' }}>
                  <Col span={4}>
                    <Form.Item name="fullName">
                      <Input placeholder="单位名称" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={4}>
                    <Form.Item name="workAddress">
                      <Input placeholder="单位地址" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={4}>
                    <Form.Item name="contactMobile">
                      <Input placeholder="联系人" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={4}>
                    <Form.Item name="contactName">
                      <Input placeholder="联系电话" allowClear />
                    </Form.Item>
                  </Col>
                  <Col span={8} style={{ textAlign: 'right' }}>
                    <Button type="primary" icon={<SearchOutlined />} onClick={onSearch}>
                      查询
                    </Button>
                    <Button style={{ marginLeft: '7px' }} icon={<RedoOutlined />} onClick={onReset}>
                      重置
                    </Button>
                  </Col>
                </Row>
              </Form>
              <div className={'list-table'}>
                <Table
                  bordered
                  size="small"
                  columns={columns}
                  dataSource={data?.rows}
                  loading={loading}
                  scroll={{ x: 500, y: 500 }}
                  rowKey={(record: any) => record?.id}
                  rowSelection={{
                    type: selectType as RowSelectionType,
                    selectedRowKeys: selectedRow[0]?.id ? selectedRow?.map((item) => item?.id) : undefined,
                    onChange: onSelectChange,
                    getCheckboxProps: (record) => ({ disabled: tableDisable?.indexOf(record?.id) == -1 ? false : true }),
                  }}
                  onRow={(record) => {
                    const flag = selectedRow?.findIndex((item) => item?.id === record?.id);
                    let newarr: Record<string, any> = [];
                    if (tableDisable?.indexOf(record?.id) != -1) {
                      newarr = selectedRow;
                    } else if (flag == -1) {
                      newarr = [...selectedRow, record];
                    } else {
                      newarr = selectedRow?.filter((item, index) => {
                        if (index != flag) {
                          return item;
                        }
                      });
                    }
                    return { onClick: () => setSelectedRow(newarr as any) };
                  }}
                  pagination={
                    {
                      pageSize: supplierTableProps?.pageSize,
                      current: supplierTableProps?.current,
                      total: supplierTableProps?.total,
                      showQuickJumper: true,
                      showSizeChanger: true,
                      pageSizeOptions: commonPageSizeOptions,
                      onChange: handlePaginationChange,
                    } as any
                  }
                ></Table>
              </div>
            </div>
          )}
        </Spin>
      </div>
    </OneModal>
  );
};

export default SupplierModal;
